package com.szgr.baoyin.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Property;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Cache;
import com.lidroid.xutils.*;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;

/**
 * Created by yang on 15/9/23.
 */
public class MyTool {
    private MyTool(){}
    private static Context mContext;
    public static void initContext(Context context){
        mContext = context;
    }
    /**
     * 获取屏幕的宽度
     * @param manager
     * @return
     */
    public static int getScreenWidth(WindowManager manager){
        DisplayMetrics displayMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }

    /**
     * 获取屏幕的高度
     * @param manager
     * @return
     */
    public static int getScreenHeight(WindowManager manager){
        DisplayMetrics displayMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.heightPixels;
    }

    /**
     * 获取状态栏的高度
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * xutils 加载图片
     * @param mContext
     * @param img
     * @param url
     */
    public static void showPicture(Context mContext,ImageView img,String url){
        com.lidroid.xutils.BitmapUtils utils = new com.lidroid.xutils.BitmapUtils(mContext);
        BitmapDisplayConfig config = new BitmapDisplayConfig();
        config.setLoadingDrawable(mContext.getResources().getDrawable(R.drawable.loading));
        config.setLoadFailedDrawable(mContext.getResources().getDrawable(R.drawable.loading));
        utils.display(img, url, config);
    }

    /**
     * xutils 加载图片
     * @param mContext
     * @param img
     * @param url
     */
    public static void showPicture1(Context mContext,ImageView img,String url){
        com.lidroid.xutils.BitmapUtils utils = new com.lidroid.xutils.BitmapUtils(mContext);
        BitmapDisplayConfig config = new BitmapDisplayConfig();
        config.setLoadingDrawable(mContext.getResources().getDrawable(R.drawable.head_view));
        config.setLoadFailedDrawable(mContext.getResources().getDrawable(R.drawable.head_view));
        utils.display(img, url, config);
    }

    /**
     * 获取本机手机号码
     * @param mContext
     * @return
     */
    public static String getPhoneNumber(Context mContext){
        TelephonyManager manager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        return manager.getLine1Number();
    }

    /**
     * 判断editText 是否为空
     * @param editText
     * @return
     */
    public static boolean isEmpty(EditText editText){
        String trim = editText.getText().toString().trim();
        if(trim != null && trim.length() > 0){
            return false;
        }
        return true;
    }

    /**
     * md5加密
     * @param val
     * @return
     */
    public static String md5EncodeString(String val){
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        md5.update(val.getBytes());
        byte[] m = md5.digest();//加密
        return getString(m);
    }

    private static String getString(byte[] b){
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < b.length; i ++){
            sb.append(b[i]);
        }
        return sb.toString();
    }

    /**
     * 保存在SharedPreferences
     * @param key
     * @param value
     */
    public static void saveSP(String key,String value){
        SharedPreferences sp = MyApplication.getmInstance().getSharedPreferences("BaoYin",Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(key, value);
        edit.commit();
    }

    /**
     * 从SharedPreferences里取数据
     * @param key
     * @return
     */
    public static String getSP(String key){
        SharedPreferences sp = MyApplication.getmInstance().getSharedPreferences("BaoYin", Context.MODE_PRIVATE);
        return sp.getString(key, "");
    }

    /**
     * EditText 取值
     * @param editText
     * @return
     */
    public static String getText(EditText editText){
        return editText.getText().toString().trim();
    }

    /**
     * TextView 取值
     * @param editText
     * @return
     */
    public static String getText(TextView editText){
        return editText.getText().toString().trim();
    }

    /**
     * dip转px函数。
     *
     * @param dpValue
     *            dip值
     * @return px值
     */
    public static int dip2px(float dpValue) {
        final float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 弹出底部菜单
     *
     * @param context
     * @param view
     * @return
     */
    public static Dialog getMenuDialog(Activity context, View view) {
        final Dialog dialog = new Dialog(context, R.style.MenuDialogStyle);
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        int screenW = getScreenWidth(context.getWindowManager());
        lp.width = screenW;
        window.setGravity(Gravity.BOTTOM); // 此处可以设置dialog显示的位置
        window.setWindowAnimations(R.style.MenuDialogAnimation); // 添加动画
        return dialog;
    }

    /**
     * 弹出中部菜单
     *
     * @param context
     * @param view
     * @return
     */
    public static Dialog getCenterDialog(Activity context, View view) {
        final Dialog dialog = new Dialog(context, R.style.MenuDialogStyle);
        dialog.setContentView(view);
        Window window = dialog.getWindow();
//        WindowManager.LayoutParams lp = window.getAttributes();
//        int screenW = getScreenWidth(context.getWindowManager());
//        lp.width = screenW;
        window.setGravity(Gravity.CENTER); // 此处可以设置dialog显示的位置
        window.setWindowAnimations(R.style.MenuDialogAnimation); // 添加动画
        return dialog;
    }

    /**
     * 关闭软键盘
     */
    public static void closeInput(Activity context){
        //关闭软键盘
        if(context.getCurrentFocus()!=null){
            ((InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(context.getCurrentFocus()
                                    .getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 判断网络是否连接
     * @param context
     * @return
     */
    public static boolean getNetState(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if(activeNetInfo.isConnected() || mobNetInfo.isConnected()){
            return true;
        }
        return false;
    }

    public static String formatDouble(double num){
        DecimalFormat format = new DecimalFormat("0.00");
        return format.format(num);
    }

    /**
     * 获取手机的sdcard 根目录 或者 内部根目录
     * @param context
     * @return
     */
    public static String getSavePath(Context context){
        File sdFile = null;
        String state = Environment.getExternalStorageState();
        if(Environment.MEDIA_MOUNTED.equals(state)){
            sdFile = Environment.getExternalStorageDirectory();
        }else{
            sdFile = context.getFilesDir();
        }
        return sdFile.getAbsolutePath();
    }

    /**
     * SD卡保存Bitmap
     * @param bitmap
     * @param path
     * @return
     */
    public static String savePicToSDCard(Bitmap bitmap,String path ,int option){
        FileOutputStream fos = null;
//        File file = new File(path);
//        if(!file.exists()){
//            file.mkdirs();
//        }
        String uuid = UUID.randomUUID().toString();
        String fileName = path + uuid + ".jpg";

        try {
            fos = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.JPEG,option,fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(fos != null){
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return path;
    }

    public static String compressImage(Bitmap image , int size ,String path) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while ( baos.toByteArray().length / 1024 > size) {    //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中

        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片

        return savePicToSDCard(bitmap,path,options);
    }

    /**
     * 将时间戳转为代表"距现在多久之前"的字符串
     * @param timeStr   时间戳
     * @return
     */
    public static String getStandardDate(String timeStr) {

        StringBuffer sb = new StringBuffer();

        long t = Long.parseLong(timeStr);
        long time = System.currentTimeMillis() - t;
        long mill = (long)Math.ceil(time /1000);//秒前

        long minute = (long)Math.ceil(time/60/1000.0f);// 分钟前

        long hour = (long)Math.ceil(time/60/60/1000.0f);// 小时

        long day = (long) Math.ceil(time/24/60/60/1000.0f);// 天前

        boolean temp = false;

        if (day - 1 > 0) {
            if(day - 1 < 3) {
                sb.append(day + "天");
            }else{
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = sdf.format(t);
                sb.append(format);
                temp = true;
            }
        } else if (hour - 1 > 0) {
            if (hour >= 24) {
                sb.append("1天");
            } else {
                sb.append(hour + "小时");
            }
        } else if (minute - 1 > 0) {
            if (minute == 60) {
                sb.append("1小时");
            } else {
                sb.append(minute + "分钟");
            }
        } else if (mill - 1 > 0) {
            if (mill == 60) {
                sb.append("1分钟");
            } else {
                sb.append(mill + "秒");
            }
        } else {
            sb.append("刚刚");
        }
        if (!sb.toString().equals("刚刚") && !temp) {
            sb.append("前");
        }
        return sb.toString();
    }

    /**
     * 根据图片字节数组，对图片可能进行二次采样，不致于加载过大图片出现内存溢出
     * @param bytes
     * @return
     */
    public static Bitmap getBitmapByBytes(byte[] bytes,int maxWidth,int maxHeight){

        //对于图片的二次采样,主要得到图片的宽与高
        int width = 0;
        int height = 0;
        int sampleSize = 1; //默认缩放为1
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;  //仅仅解码边缘区域
        //如果指定了inJustDecodeBounds，decodeByteArray将返回为空
        BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
        //得到宽与高
        height = options.outHeight;
        width = options.outWidth;

        //图片实际的宽与高，根据默认最大大小值，得到图片实际的缩放比例
        while ((height / sampleSize > maxHeight)
                || (width / sampleSize > maxWidth)) {
            sampleSize *= 2;
        }

        //不再只加载图片实际边缘
        options.inJustDecodeBounds = false;
        //并且制定缩放比例
        options.inSampleSize = sampleSize;
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
    }

    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos =new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);

        return baos.toByteArray();
    }

    public static InputStream BytesToInStream(byte[] bytes)
    {
        InputStream is = new ByteArrayInputStream(bytes);
        return is;
    }

    public static int getCurrentYear(){
        Calendar instance = Calendar.getInstance();
        int i = instance.get(Calendar.YEAR);
        RLog.s("------year---->" + i);
        return i;
    }

    public static int getCurrentMonth(){
        Calendar instance = Calendar.getInstance();
        int i = instance.get(Calendar.MONTH);
        RLog.s("------month---->" + (i+1));
        return i+1;
    }

    public static int getCurrentDay(){
        Calendar instance = Calendar.getInstance();
        int i = instance.get(Calendar.DAY_OF_MONTH);
        RLog.s("------day---->" + i);
        return i;
    }
}
